package com.qiyu.jvm.finalize;

/**
 * 在对象即将消亡之前会调用，但是只会调用一次
 *
 * @Author linhao
 * @Date created in 3:38 下午 2021/1/4
 */
public class FinalizeEscapeGC {

    private static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("i am alive!!");
    }

    /**
     * 垃圾回收机制会触发这个函数，但是如果这里面写了一些堵塞类型的操作，会导致主进程卡主，影响较大，所以不推荐这么做，本身java
     * 也不是太推荐修改finalize函数的逻辑。可以使用try-catch-finally这种方式进行操作
     *
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize methos is executed!");
        SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();
        SAVE_HOOK = null;
        System.gc();
        Thread.sleep(1500);
        if (FinalizeEscapeGC.SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("finalizeEscapeGC is dead!");
        }
        Thread.sleep(1500);
        SAVE_HOOK = null;
        System.gc();
        if (FinalizeEscapeGC.SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("finalizeEscapeGC is dead!");
        }
    }
}
